"use client";

import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import { toast } from "react-hot-toast";
import { apiClient } from "../lib/api";
import { Token, TokensQuery } from "../types/api";
import { useTokenWebSocket } from "../hooks/useWebSocket";
import { TokenDetailModal } from "./TokenDetailModal";
import { TokenChatRoom } from "./TokenChatRoom";
import { formatPrice, formatMarketCap } from "../utils/formatters";
import { MessageCircle } from "lucide-react";

interface TokenListProps {
  showTrending?: boolean;
  limit?: number;
}

export function TokenList({
  showTrending = false,
  limit,
}: TokenListProps) {
  const [tokens, setTokens] = useState<Token[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [orderBy, setOrderBy] = useState<
    "createdAt" | "marketCap" | "price" | "holders"
  >("createdAt");
  const [order, setOrder] = useState<"asc" | "desc">("desc");
  const [selectedToken, setSelectedToken] = useState<Token | null>(null);
  const [chatToken, setChatToken] = useState<Token | null>(null);

  const ws = useTokenWebSocket();

  // Load tokens
  const loadTokens = useCallback(async (query?: Partial<TokensQuery>) => {
    try {
      setLoading(true);
      setError(null);

      let response;

      if (showTrending) {
        response = await apiClient.getTrendingTokens(limit || 10);
        setTokens(response.data || []);
      } else if (searchQuery.trim()) {
        response = await apiClient.searchTokens({
          q: searchQuery.trim(),
          limit: limit || 20,
        });
        setTokens(response.data || []);
      } else {
        response = await apiClient.getTokens({
          page: currentPage,
          limit: limit || 20,
          orderBy,
          order,
          ...query,
        });
        setTokens(response.data || []);

        if (response.pagination) {
          setTotalPages(response.pagination.pages);
        }
      }
    } catch (error: unknown) {
      console.error("Failed to load tokens:", error);
      
      let errorMessage = "Failed to load tokens";
      
      if (error && typeof error === 'object') {
        if ('response' in error && error.response && typeof error.response === 'object' && 
            'data' in error.response && error.response.data && typeof error.response.data === 'object' &&
            'message' in error.response.data) {
          errorMessage = String(error.response.data.message);
        } else if ('message' in error) {
          errorMessage = String(error.message);
        }
      }
      
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [currentPage, orderBy, order, showTrending, limit, searchQuery]);

  // Initial load
  useEffect(() => {
    loadTokens();
  }, [loadTokens]);

  // Search with debounce
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      setCurrentPage(1);
      loadTokens();
    }, 500);

    return () => clearTimeout(timeoutId);
  }, [searchQuery, loadTokens]);

  // Listen for new tokens and price updates via WebSocket
  useEffect(() => {
    if (ws.connected) {
      const unsubscribeNewToken = ws.subscribe("new_token", (data) => {
        setTokens((prev) => [data.token, ...prev]);
        toast.success(`新代币创建: ${data.token.name} (${data.token.symbol})`);
      });

      // 监听全局价格更新事件
      const unsubscribePriceUpdate = ws.subscribe("token_price_update", (data) => {
        setTokens((prev) => 
          prev.map(token => 
            token.mint === data.mint 
              ? { ...token, price: data.price, marketCap: data.marketCap } 
              : token
          )
        );
      });

      return () => {
        unsubscribeNewToken();
        unsubscribePriceUpdate();
      };
    }
  }, [ws.connected, ws]);

  const formatTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 60) {
      return `${diffMins}mins ago`;
    }
    if (diffHours < 24) {
      return `${diffHours}h ago`;
    }
    return `${diffDays}d ago`;
  };

  if (error) {
    return (
      <div className="text-center py-8">
        <div className="text-red-500 mb-4">
          <svg
            className="w-12 h-12 mx-auto"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
        </div>
        <p className="text-gray-400 mb-4">{error}</p>
        <button
          onClick={() => loadTokens()}
          className="pixel-btn"
        >
          retry
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
  <div className="w-full">
        <div className="flex flex-col items-center text-center gap-2 mb-2">
          <h2 className="text-2xl font-bold font-pixel">
            {showTrending ? "hot tokens" : "all tokens"}
          </h2>
          {ws.connected && (
            <div className="flex items-center text-green-400 text-sm">
              <div className="w-2 h-2 bg-green-400 rounded-full mr-2 animate-pulse"></div>
              connected
            </div>
          )}
        </div>
      </div>

      {/* Search and Filters */}
      {!showTrending && (
        <div className="space-y-3 w-full px-6 md:px-12 lg:px-[50px]">
          <div>
            <input
              type="text"
                placeholder="搜索代币名称、符号或地址..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pixel-input w-full"
            />
          </div>
          <br/>

          <div className="flex gap-2 justify-center">
            <select
              value={orderBy}
              onChange={(e) => setOrderBy(e.target.value as "createdAt" | "marketCap" | "price" | "holders")}
              className="pixel-input"
            >
              <option value="createdAt">createdAt</option>
              <option value="marketCap">marketCap</option>
              <option value="price">price</option>
              <option value="holders">holders</option>
            </select>

            <select
              value={order}
              onChange={(e) => setOrder(e.target.value as "asc" | "desc")}
              className="pixel-input"
            >
              <option value="desc">descending</option>
              <option value="asc">ascending</option>
            </select>
          </div>
        </div>
      )}
<br/>

      {/* Loading */}
      {loading && (
        <div className="flex justify-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
        </div>
      )}

      {/* Token Grid */}
      {!loading && (
  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 w-full">
          {tokens.map((token) => (
            <div
              key={token.id}
              className="pixel-card transition-transform hover:scale-105 relative"
            >
              {/* Chat Button */}
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setChatToken(token);
                }}
                className="absolute top-3 right-3 bg-purple-600 hover:bg-purple-700 text-white p-2 rounded-full shadow-lg transition-colors z-10"
                title={`chat with ${token.symbol}`}
              >
                <MessageCircle size={16} />
              </button>

              {/* Token Content - Make it clickable for details */}
              <div
                onClick={() => setSelectedToken(token)}
                className="cursor-pointer"
              >
              {/* Token Header */}
              <div className="flex items-center space-x-3 mb-4">
                {token.image ? (
                  <Image
                    src={token.image}
                    alt={token.name}
                    width={48}
                    height={48}
                    className="rounded-full object-cover"
                  />
                ) : (
                  <div className="w-12 h-12 bg-gradient-to-br from-purple-400 to-purple-600 flex items-center justify-center" style={{imageRendering: 'pixelated'}}>
                    <span className="text-white font-bold text-lg">
                      {token.symbol.charAt(0)}
                    </span>
                  </div>
                )}

        <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
          <h3 className="font-semibold truncate font-body">
                      {token.name}
                    </h3>
                    {token.isGraduated && (
                      <span className="inline-flex items-center px-2 py-1 text-xs font-medium bg-yellow-400 text-black border-2 border-black">
                        🎓 graduated
                      </span>
                    )}
                  </div>
                  <p className="text-xs text-gray-400 font-mono">{token.symbol}</p>
                </div>
              </div>

              {/* Token Stats */}
              <div className="space-y-2 mb-4">
                <div className="flex justify-between">
                  <span className="text-xs text-gray-400">price</span>
                  <span className="text-sm font-medium">
                    {formatPrice(token.price)}
                  </span>
                </div>

                <div className="flex justify-between">
                  <span className="text-xs text-gray-400">marketCap</span>
                  <span className="text-sm font-medium">
                    {formatMarketCap(token.marketCap)}
                  </span>
                </div>

                <div className="flex justify-between">
                  <span className="text-xs text-gray-400">holders</span>
                  <span className="text-sm font-medium">
                    {token.holders.toLocaleString()}
                  </span>
                </div>
              </div>

              {/* Description */}
              {token.description && (
                <p className="text-sm text-gray-300 mb-4 line-clamp-2 font-body">
                  {token.description}
                </p>
              )}

              {/* Footer */}
              <div className="flex items-center justify-between text-xs text-gray-400">
                <span>createdAt: {formatTimeAgo(token.createdAt)}</span>
                <span className="font-mono text-xs bg-gray-700 px-2 py-1 border border-gray-600">
                  {`${token.mint.slice(0, 4)}...${token.mint.slice(-4)}`}
                </span>
              </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Empty State */}
      {!loading && tokens.length === 0 && (
        <div className="text-center py-8">
          <div className="text-gray-400 mb-4">
            <svg
              className="w-12 h-12 mx-auto"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2M4 13h2m13-8v2a1 1 0 001 1h2M4 5v2a1 1 0 001 1h2"
              />
            </svg>
          </div>
          <p className="text-gray-400">
            {searchQuery ? "未找到匹配的代币" : "暂无代币"}
          </p>
        </div>
      )}

      {/* Pagination */}
      {!loading && !showTrending && !searchQuery && totalPages > 1 && (
        <div className="flex justify-center space-x-2">
          <button
            onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
            className="pixel-btn disabled:opacity-50 disabled:cursor-not-allowed"
          >
            prev
          </button>

          <span className="px-3 py-2">
            page {currentPage} of {totalPages}
          </span>

          <button
            onClick={() =>
              setCurrentPage((prev) => Math.min(totalPages, prev + 1))
            }
            disabled={currentPage === totalPages}
            className="pixel-btn disabled:opacity-50 disabled:cursor-not-allowed"
          >
            next
          </button>
        </div>
      )}

      <TokenDetailModal
        token={selectedToken}
        onClose={() => setSelectedToken(null)}
      />
      
      <TokenChatRoom
        token={chatToken}
        onClose={() => setChatToken(null)}
      />
    </div>
  );
}
